/*
 * @lc app=leetcode.cn id=203 lang=typescript
 *
 * [203] 移除链表元素
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

//  思路：迭代
//  prev存储上一个节点，判断curr的值，=val则prev接后面，否则curr接后面

//  复杂度：O(n) O(1)

function removeElements(head: ListNode | null, val: number): ListNode | null {
    let newHead = new ListNode()
    let prev: ListNode = newHead, curr: ListNode | null = head
    newHead.next = head

    while (curr) {
        if (curr.val === val) {
            prev.next = curr.next
            curr = prev.next
        } else {
            prev = curr
            curr = curr.next
        }
    }
    return newHead.next
};
// @lc code=end

import { ListNode } from './type'
const head = new ListNode(1, new ListNode(2, new ListNode(2, new ListNode(4))))
console.log(ListNode.printList(removeElements(head, 2)))

